package controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import model.User;
import service.UserService;
import util.constant.Constant;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	
	
	@RequestMapping("/index")
	private ModelAndView index(ModelAndView mv) {
		mv.setViewName("qqTalk");
		return mv;
	};
	
	/**
	 * 进入注册页面
	 * @return
	 */
	@RequestMapping("/registerUI")
	private String registerUI() {
		return "registerUI";
	}
	
	@ResponseBody
	@RequestMapping("/register")
	private Map<String, String> register(String username, String alias, String password, Integer sex) {
		Map<String, String> msg = new HashMap<>();
		boolean flag = userService.checkUserRegmsg(username, password, alias, sex);
		if(flag) {
			User user = new User();
			user.setUsername(username);
			user.setAddTime(new Date());
			user.setPassword(password);
			user.setSex(sex);
			user.setAlias(alias);
			userService.saveUser(user);
			
			msg.put("code", "success");
		}else {
			msg.put("code", "error");
		}
		return msg;
	}
	
	@ResponseBody
	@RequestMapping("/login")
	private Map<String, Object> login(String username, String password) {
		Map<String, Object> msg = new HashMap<>();
		User user = userService.loginUser(username, password);
		
		if(user != null)
		{
			msg.put("username", user.getUsername());
			msg.put("alias", user.getAlias());
			msg.put("onlineTime", user.getOnlineTime());
			msg.put("socketAddr", Constant.WEB_SOCKET.ADDRESS);
			msg.put("socketPost", Constant.WEB_SOCKET.POST);
			msg.put("code", Constant.RESPONSE_STATE.SUCCESS);
		}else {
			msg.put("code", Constant.RESPONSE_STATE.ERROR);
		}
		return msg;
	}
	
}
